//
//  WXAuth.m
//  hongyantub2b
//
//  Created by Apple on 2018/8/23.
//  Copyright © 2018年 Apple. All rights reserved.
//

#import "WXAuth.h"
#import "WXApi.h"

#define DEFINE_SHARED_INSTANCE_USING_BLOCK(block) \
static dispatch_once_t pred = 0; \
static id _sharedObject = nil; \
dispatch_once(&pred, ^{ \
_sharedObject = block(); \
}); \
return _sharedObject; \

@interface WXAuth ()<WXApiDelegate>

@property (nonatomic,copy) loginResultBlock loginBlock;
@property (nonatomic,assign) BOOL isOK; //是否成功
@property (nonatomic,strong) NSString *userName;//用户昵称
@property (nonatomic,strong) NSString *userIconURL;//用户头像
@property (nonatomic,copy) NSString *placeOpenID;
@property (nonatomic,copy) NSString *placeUnionID;
@end

@implementation WXAuth

+ (WXAuth *)sharedInstance{
    
    DEFINE_SHARED_INSTANCE_USING_BLOCK(^{
        
        return [[self alloc] init];
    });
}

- (id)init{
    
    self = [super init];
    if (self) {
        
    }
    return self;
}

/**
 *  微信登录
 *
 */
- (void)loginAuthWithBlock:(loginResultBlock)resultBlock{
    if ([WXApi isWXAppSupportApi]) {
        WXAuth *manager = [WXAuth sharedInstance];
        manager.loginBlock = resultBlock;
        
        SendAuthReq *req = [[SendAuthReq alloc] init];
        /**
         *  应用获取权限 此处为个人用户信息
         */
        req.scope = @"snsapi_userinfo";
        req.state = @"wx_oauth_authorization_state";
        /**
         *  可以不用填写
         */
        //        req.state = @"413e6ad8cae81487d315780b0a6717c0";
        //req.openID = WXAppKey;
        
//        [WXApi sendAuthReq:req viewController:nil delegate:manager];
        [WXAUTH sendWXAuthReq];
    }
}
- (void)sendWXAuthReq{
    
    if([WXApi isWXAppInstalled]){//判断用户是否已安装微信App
        
        SendAuthReq *req = [[SendAuthReq alloc] init];
        req.state = @"wx_oauth_authorization_state";//用于保持请求和回调的状态，授权请求或原样带回
        req.scope = @"snsapi_userinfo";//授权作用域：获取用户个人信息
        
        [WXApi sendReq:req];
    }else{
        
//        NSLog(@"未安装微信应用或版本过低");
    }
}

- (BOOL)handleOpenURL:(NSURL *)url{
    
    //处理回调
    if([url.host isEqualToString:@"platformId=wechat"]){//微信WeChat分享回调
        [[NSNotificationCenter defaultCenter] postNotificationName:@"WeChatShareSuccess" object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TuijianFriendWeChatShareSuccess" object:nil];
        return [WXApi handleOpenURL:url delegate:self];
    }else if([url.host isEqualToString:@"oauth"]){
        return [WXApi handleOpenURL:url delegate:self];
    }else{
        
        return NO;
    }
}

- (void)onReq:(BaseReq *)req{
    
}
/**
 Delegate回调方法
 */
- (void)onResp:(id)resp{
//    if([resp isKindOfClass:[SendAuthResp class]]){//判断是否为授权登录类
//
        SendAuthResp *req = (SendAuthResp *)resp;
//        if([req.state isEqualToString:@"wx_oauth_authorization_state"]){//微信授权成功
//
//            if(req.errCode == 0){
//
//                NSLog(@"获取code：%@", req.code);
//                [[NSUserDefaults standardUserDefaults] setObject:req.code forKey:@"WhchatCode"];
//                [[NSUserDefaults standardUserDefaults] synchronize];
////                req.code;
//            }
//        }
//    }
    if([req isKindOfClass:[SendAuthResp class]]) {
        if (req.errCode == WXSuccess) {
            // temp.state 慎重的话校验state
            [self getOpenIDNetwork:((SendAuthResp *)resp).code];
            
        } else {
            if (req.errCode == WXErrCodeAuthDeny) {
                if (self.loginBlock) {
                    self.loginBlock(false,  @"用户拒绝微信授权", @"0", nil, nil, nil);
                }
            } else if (req.errCode == WXErrCodeUserCancel) {
                if (self.loginBlock) {
                    self.loginBlock(false, @"用户取消微信授权", @"0", nil, nil,nil);
                }
            } else {
                if (self.loginBlock) {
                    self.loginBlock(false, @"微信授权失败", @"0", nil, nil,nil);
                }
            }
        }
    }
}
/**
 *  请求参数说明
 * grant_type:获取access_token填写client_credential
 
 appid:第三方用户唯一凭证
 
 secret:第三方用户唯一凭证密钥,既appsecret
 
 authorization_code: 授权代码
 *  @param code <#code description#>
 */

- (void)getOpenIDNetwork:(NSString *)code
{
    NSDictionary *postDic = @{@"appid" : WeChatAppID,@"secret" : WeChatAppSecret,@"code" : code,@"grant_type" : @"authorization_code"};
    
    __weak __typeof(self) weakself = self;
    [weakself requestWithFullUrl:@"https://api.weixin.qq.com/sns/oauth2/access_token?" withParams:postDic andBlock:^(id data, NSError *error) {
        
        if (error) {
            if (self.loginBlock) {
                self.loginBlock(false, @"微信授权失败，网络错误", @"0", nil, nil,nil);
            }
        } else {
            // 优先解析错误码 {"errcode":40029,"errmsg":"invalid code"}
            if ([data objectForKey:@"errcode"]) {
                // 出现错误
                NSString *errmsg = [data objectForKey:@"errmsg"];
                if (weakself.loginBlock) {
                    weakself.loginBlock(false, [NSString stringWithFormat:@"微信授权失败，%@", errmsg], @"0", nil, nil,nil);
                }
            } else {
                
                [weakself getUnionIDWithOpenID:[data objectForKey:@"openid"]
                                         token:[data objectForKey:@"access_token"]];
                
            }
        }
    }];
}

- (void)getUnionIDWithOpenID:(NSString *)openID token:(NSString *)token
{
    NSDictionary *postDic = @{@"access_token" : token,
                              @"openid" : openID};
    
    __weak __typeof(self) weakself = self;
    [weakself requestWithFullUrl:@"https://api.weixin.qq.com/sns/userinfo?" withParams:postDic andBlock:^(id data, NSError *error) {
        if (error) {
            if (weakself.loginBlock) {
                weakself.loginBlock(false, @"微信授权失败，网络错误", @"0", nil, nil,nil);
            }
        } else {
            // 优先解析错误码 {"errcode":40029,"errmsg":"invalid code"}
            if ([data objectForKey:@"errcode"]) {
                // 出现错误
                NSString *errmsg = [data objectForKey:@"errmsg"];
                if (weakself.loginBlock) {
                    weakself.loginBlock(false, [NSString stringWithFormat:@"微信授权失败，%@", errmsg], @"0", nil, nil,nil);
                }
            } else {
                
                self.placeOpenID = [data objectForKey:@"openid"];
                self.placeUnionID = [data objectForKey:@"unionid"];
                
                // 授权成功，取用户信息
                [self getUserInfo:openID andToken:token];
                
                //                if (weakself.loginBlock) {
                //                    weakself.loginBlock(true, self.placeOpenID, self.placeUnionID, weakself.userName, weakself.userIconURL);
                //                }
            }
        }
    }];
}

- (void)getUserInfo:(NSString *)openid andToken:(NSString *)token
{
    NSDictionary *postDic = @{@"access_token" : token,
                              @"openid" : openid};
    __weak __typeof(self) weakself = self;
    [weakself requestWithFullUrl:@"https://api.weixin.qq.com/sns/userinfo?" withParams:postDic andBlock:^(id data, NSError *error) {
        if (error) {
//            NSLog(@"error::%@",error);
        } else {
            // 优先解析错误码 {"errcode":40029,"errmsg":"invalid code"}
            if ([data objectForKey:@"errcode"]) {
                // 出现错误
            } else {
                weakself.isOK = true;
                weakself.userName = [data objectForKey:@"nickname"];
                weakself.userIconURL = [data objectForKey:@"headimgurl"];

                if (weakself.loginBlock) {
                    weakself.loginBlock(true, weakself.placeOpenID, weakself.placeUnionID, weakself.userName, weakself.userIconURL, data);
//                    NSLog(@"%@",data);
                }
            }
        }
    }];
}
//请求数据方法
- (void)requestWithFullUrl:(NSString *)urlPath withParams:(NSDictionary *)params andBlock:(networkBlock)block{
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html", nil];
    
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    if (!urlPath || urlPath.length <= 0) {
        return;
    }
    urlPath = [urlPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    // 发起请求
    [manager POST:urlPath parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (block) {
            block(responseObject, nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (block) {
            block(nil, error);
        }
    }];
}

@end
